Imports System.Data.SqlClient
Imports system.Security.Cryptography
Imports System.IO
Imports System.Text

Friend Class DBScanIndexes
    Inherits DBBase

    Private moServer As SQLAutoDocLib.Server
    Private moDatabase As SQLAutoDocLib.Database
    Private moLogin As SQLAutoDocLib.Login
    Private moTable As SQLAutoDocLib.Table

    Public Sub New( _
                ByVal oServer As SQLAutoDocLib.Server, _
                ByVal oDatabase As SQLAutoDocLib.Database, _
                ByVal oLogin As SQLAutoDocLib.Login, _
                ByVal oTable As SQLAutoDocLib.Table)

        moServer = oServer
        moDatabase = oDatabase
        moLogin = oLogin
        moTable = oTable
    End Sub

    Public Sub Scan( _
                ByRef oIndexList As ArrayList, _
                ByRef sHash As String)

        oIndexList = ScanForIndexes()
        sHash = ComputeSHA1(oIndexList)
    End Sub

    Private Function ScanForIndexes() As ArrayList
        Dim oList As New ArrayList

        Dim sSQL = "sp_helpindex"

        Dim oCon As New SqlConnection(moDatabase.DecryptedConnectionString)
        oCon.Open()

        Dim oCMD As New SqlCommand(sSQL, oCon)
        oCMD.CommandType = CommandType.StoredProcedure

        Dim oParm As New SqlParameter("@objname", SqlDbType.NVarChar, 1552)
        oParm.Value = moLogin.Login & "." & moTable.Name
        oCMD.Parameters.Add(oParm)

        Dim oDT As New SqlDataAdapter(oCMD)

        Dim oData As New DataTable

        oDT.Fill(oData)

        oDT.Dispose()
        oCMD.Dispose()
        oCon.Close()
        oCon.Dispose()

        oDT.Dispose()

        Dim oFactory As New Field_Factory

        For Each oRow As DataRow In oData.Rows
            Dim oIndex As New SQLAutoDocLib.Index
            With oIndex
                .TableID = moTable.ID
                .Name = oRow.Item("Index_Name")
                .Index_Desc = oRow.Item("Index_Description")
                .Keys = oRow.Item("Index_Keys")
            End With

            oList.Add(oIndex)
        Next

        Return oList
    End Function

    Private Function ComputeSHA1(ByVal oList As ArrayList) As String
        Dim sAllFields As New StringBuilder

        For Each oField As SQLAutoDocLib.Index In oList
            Dim sXML As String = oField.SerializeMe

            sAllFields.Append(sXML)
        Next

        Dim oCrypto As New JCO
        Return oCrypto.GetHash(sAllFields.ToString)
    End Function
End Class
